package site.jlopen.assets.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.SneakyThrows;
import site.jlopen.assets.shiro.token.JwtToken;
import site.jlopen.domain.user.UserAccount;
import site.jlopen.entity.vo.LoginRes;
import site.jlopen.mapper.user.UserAccountMapper;
import site.jlopen.service.intf.user.UserService;
import site.jlopen.utils.jwt.JwtTool;
 
/**
 * @Description 授权
 * @Date 2021/8/18
 **/
@Component
public class JwtRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;
 
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
 
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        boolean verifyToken = JwtTool.verify(token);
        if(!verifyToken) {
        	throw new UnknownAccountException("鉴权失败");
        }
        String userName = JwtTool.getUserName(token);
        LoginRes user = userService.getLoginByName(userName);
        //UserAccount info = userMapper.selectByKey(userId);
        if(null == user) {
        	throw new UnknownAccountException("鉴权失败");
        }
        return new SimpleAuthenticationInfo(user, token, this.getName());
    }
}